﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Drawing;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Project_Summarize : frmBaseChild
    {
        string strSql;

        public frmMES_Project_Summarize()
        {
            InitializeComponent();
        }

        private void frmMES_Project_Progress_Load(object sender, EventArgs e)
        {
            getQuerySQL_OnGoing();
            rfreshTreeList();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                strSql = getTitleSQL() + @"
						FROM View_PJT_Project_Progress_Union";
            }
            else
            {
                getQuerySQL_OnGoing();
            }

            rfreshTreeList();
        }

        private void getQuerySQL_OnGoing()
        {
            strSql = getTitleSQL() + @"
						FROM View_PJT_Project_Progress_Union
						WHERE KeyIndex IN(
						SELECT ParentIndex
						FROM
						(SELECT ParentIndex,COUNT(ParentIndex) AS Item_QTY
						FROM View_PJT_Project_Progress_Union 
						WHERE Finish_Date IS NULL
						GROUP BY ParentIndex) AS a
						WHERE a.Item_QTY>1) 
						UNION "
                        + getTitleSQL() + @"
						FROM View_PJT_Project_Progress_Union
						WHERE Start_Date IS NOT NULL AND Leader IS NOT NULL AND Finish_Date IS NULL";
        }

        private void rfreshTreeList()
        {
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);

            //TreeList绑定数据
            treeList1.DataSource = dt;

            treeList1.KeyFieldName = "KeyIndex";
            treeList1.ParentFieldName = "ParentIndex";
            treeList1.EndUpdate();
            treeList1.ExpandAll();
            treeList1.Columns[0].Width = 180;
            //treeList1.Columns[0].BestFit();

            ////Create a repository item corresponding to a combo box editor. 
            //RepositoryItemComboBox riCombo = new RepositoryItemComboBox();
            //riCombo.Items.AddRange(new string[] { "San Francisco", "Monterey", "Toronto", "Boston", "Kuaui", "Singapore", "Tokyo" });
            ////Add the item to the internal repository 
            //treeList1.RepositoryItems.Add(riCombo);
            ////Now you can define the repository item as an in-place column editor 
            //treeList1.Columns[0].ColumnEdit = riCombo;

            RepositoryItemProgressBar riProBar = new RepositoryItemProgressBar();
            treeList1.RepositoryItems.Add(riProBar);
            treeList1.Columns[5].ColumnEdit = riProBar;
            treeList1.Columns[6].ColumnEdit = riProBar;
            riProBar.ShowTitle = true;
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            //treeList1.ExpandToLevel(Convert.ToInt32(comboBox1.Text) - 1);
            switch(comboBox1.Text)
            {
                case "1":
                    treeList1.ExpandToLevel(0);
                    break;
                case "2":
                    treeList1.ExpandToLevel(1);
                    break;
                case "3":
                    treeList1.ExpandToLevel(2);
                    break;

            }
        }

        private string getTitleSQL()
        {
//            string strTitleSQL = @"SELECT KeyIndex,ParentIndex,Item_No AS 编号,Item_Caption AS 主题,Item_Desc AS 内容, 
//                        Leader AS 负责,Member AS 协助, 
//						CAST(Finish_Percentage AS VARCHAR) + '%' AS 完成比例, 
//						CAST(Plan_Rate AS VARCHAR) + '%' AS 计划比例,
//						CASE WHEN Finish_Percentage>=Plan_Rate THEN '正常' ELSE '延迟' END AS 状态, 					
//						Start_Date AS 开始日期,Due_Date AS 预计完成,
//						Finish_Date AS 实际完成,Project_Type AS 项目类型 ";

            string strTitleSQL = @"SELECT KeyIndex,ParentIndex,Item_No AS 编号,Item_Caption AS 主题,Item_Desc AS 内容, 
                        Leader AS 负责,Member AS 协助, 
						Finish_Percentage AS 完成比例, 
						Plan_Rate AS 计划比例,
						CASE WHEN Leader IS NULL THEN NULL WHEN Finish_Percentage>=Plan_Rate THEN '进度正常' ELSE '进度延迟' END AS 状态, 					
						Start_Date AS 开始日期,Due_Date AS 预计完成,
						Finish_Date AS 实际完成,Project_Type AS 项目类型 ";

            return strTitleSQL;

            //DevExpress GridView 单元格进度条的绑定及拓展自定义进度条不同颜色显示
            //https://blog.csdn.net/u012097590/article/details/93210486
        }
        
        /// <summary>
        /// 自定义进度条列
        /// </summary>
        /// <param name="view"></param>
        /// <param name="fieldName">列的字段名</param>
        /// <param name="warningValue"></param>
        /// <param name="lessColor"></param>
        /// <param name="greaterColor"></param>
        public static void CustomProgressBarColumn(DevExpress.XtraGrid.Views.Grid.GridView view, string fieldName, int warningValue=50, Brush lessColor = null, Brush greaterColor = null)
        {
            var col = view.Columns[fieldName];
            if (col == null) return;
            col.AppearanceCell.Options.UseTextOptions = true;
            col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            view.CustomDrawCell += (s, e) =>
            {
                if (e.Column.FieldName == fieldName)
                {
                    DrawProgressBar(e,warningValue,lessColor,greaterColor);
                    e.Handled = true;
                    DrawEditor(e);
                }
            };
        }
        
       static void DrawProgressBar(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e, int warningValue = 50, Brush lessColor = null, Brush greaterColor = null)
        {
            decimal percent = e.CellValue == null ? 0m : (decimal)e.CellValue;
            int width = (int)(percent * e.Bounds.Width);
            Rectangle rect = new Rectangle(e.Bounds.X, e.Bounds.Y, width, e.Bounds.Height);
 
            Brush b = Brushes.Green;
            if (greaterColor != null)
            {
                b = greaterColor;
            }
            if (percent * 100 < warningValue)
            {
                if (lessColor == null)
                {
                    b = Brushes.Red;
                }
                else
                {
                    b = lessColor;
                }
            }
            e.Graphics.FillRectangle(b, rect);
        }

       static void DrawEditor(DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            GridCellInfo cell = e.Cell as GridCellInfo;
            Point offset = cell.CellValueRect.Location;
            BaseEditPainter pb = cell.ViewInfo.Painter as BaseEditPainter;
            AppearanceObject style = cell.ViewInfo.PaintAppearance;
            if (!offset.IsEmpty)
                cell.ViewInfo.Offset(offset.X, offset.Y);
            try
            {
                pb.Draw(new ControlGraphicsInfoArgs(cell.ViewInfo, e.Cache, cell.Bounds));
            }
            finally
            {
                if (!offset.IsEmpty)
                {
                    cell.ViewInfo.Offset(-offset.X, -offset.Y);
                }
            }
        }

       private void treeList1_CustomDrawNodeCell(object sender, DevExpress.XtraTreeList.CustomDrawNodeCellEventArgs e)
       {
           //一直在里面遍历，导致卡死
           //https://bbs.csdn.net/topics/392283406

           //如果ProgressBarControl.Property.LookAndFeel.Style 为Skin，进度条的背景色会为默认设置。
           //将UserDefaultLookAndFeel 设置为false, style设置为Skin以外其他属性，
           //然后通过设置Properties.StartColor和Properties.EndColor来自定义进度条颜色了。

           RepositoryItemProgressBar repositoryItemProgressBar1 = new RepositoryItemProgressBar();
           treeList1.RepositoryItems.Add(repositoryItemProgressBar1);
           treeList1.Columns[5].ColumnEdit = repositoryItemProgressBar1;
           treeList1.Columns[6].ColumnEdit = repositoryItemProgressBar1;
           repositoryItemProgressBar1.ShowTitle = true;

           if (e.Column.FieldName == "完成比例" | e.Column.FieldName == "计划比例")
           {

               repositoryItemProgressBar1.LookAndFeel.UseDefaultLookAndFeel = false;
               if (e.CellValue != DBNull.Value)//跳过DBNULL
               {
                   decimal percent = Convert.ToDecimal(e.CellValue);
                   if (percent < 50)
                   {
                       repositoryItemProgressBar1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Skin;
                   }
                   else
                   {
                       repositoryItemProgressBar1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003;
                   }
               }
           }  
       }

       private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
       {
           panelTop.Height = 0;
       }

       private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
       {
           panelTop.Height = 60;
       }

    }
}